<template>
  <div>
    <el-dialog :close-on-click-modal="false" v-drag :title="type === 'edit' ? $t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="1200px" top="10vh" @close="close">
      <div class="dialog-content-box">
        <el-form ref="form" :model="record" label-width="100px" :rules="rules" label-position="left" :hide-required-asterisk="true" style="margin:0 30px;">
          <el-form-item :label="$t('名称')" prop="name">
            <el-input v-if="type === 'add'" v-emoji v-model="record.name" ref="temName" style="width:400px;" size="small" :placeholder="$t('请输入名称')"></el-input>
            <span v-else>{{ record.show_name }}</span>
          </el-form-item>
          <el-form-item :label="$t('描述')" prop="desc">
            <el-input v-if="type === 'add'" v-emoji size="small" type="textarea" ref="temDesc" style="width:400px;" @keydown.native="handleKeyCode($event)" :placeholder="$t('请输入内容')" :autosize="{ minRows: 2, maxRows: 4 }" v-model="record.desc">
            </el-input>
            <span v-else>{{ record.desc }}</span>
          </el-form-item>
          <el-form-item :label="$t('模板类型')" prop="type">
            <el-select v-if="type === 'add'" size="medium" v-model="record.type" ref="temType" placeholder="" style="width:400px;" @change="typeChange">
              <el-option v-for="(item, index) in typeList" :key="index" :label="$t(item)" :value="index">
              </el-option>
            </el-select>
            <span v-else>{{ $t(typeList[record.type]) }}</span>
          </el-form-item>
          <el-form-item :label="$t('分组依据')" prop="group">
            <el-select v-if="type === 'add'" size="small" v-model="record.group" ref="temGroup" placeholder="" style="width:400px;">
              <el-option v-for="(item, index) in groupList[record.type]" :key="index" :label="$t(item)" :value="index">
              </el-option>
            </el-select>
            <span v-else>{{ $t(groupList[record.type][record.group]) }}</span>
          </el-form-item>
          <el-form-item :label="$t('查询条件')">
            <el-button type="success" size="small" @click="addSelect()" class="temAdd">{{ $t('添加') }}</el-button>
            <el-button type="danger" size="small" @click="clearSelect" class="temClear">{{ $t('清空') }}</el-button>
          </el-form-item>
        </el-form>

        <TempleEdit ref="templeEdit" :type="type" :select="select" @handleAddTemp="handleAddTemp" @handleEditTemp="handleEditTemp" @handleCancelTemp="handleCancelTemp" @handleDelTemp="handleDelTemp" @handleSaveTemp="handleSaveTemp" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="type === 'add'" type="primary" @click="submit" class="addSubmit">{{ $t('确 定') }}</el-button>
        <el-button @click="close" class="addClose">{{ $t('取 消') }}</el-button>
      </span>
    </el-dialog>
    <!-- 添加模板 -->
    <el-dialog :close-on-click-modal="false" v-drag :title="$t('添加')" :v-if="dialogVisibleTemp" :visible.sync="dialogVisibleTemp" width="470px" top="20vh" @close="handleCancel">
      <el-form :model="tableForm" ref="tableForm" class="table-form" label-width="80px" label-position="left" style="margin:0 20px;">
        <el-form-item :label="$t('关键字')" prop="key" :rules="tableFormRules.key">
          <el-select size="small" v-model="tableForm.key" :placeholder="$t('请选择关键字')">
            <el-option v-for="(item, index) in keyList" :key="index" :label="$t(item)" :value="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('符号')" prop="operator" :rules="tableFormRules.operator">
          <el-select size="small" v-model="tableForm.operator" :placeholder="$t('请选择符号')">
            <el-option v-for="(item, index) in operatorList" :key="index" :label="$t(item)" :value="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('值')" prop="value" :rules="tableFormRules.value">
          <el-input v-emoji v-model="tableForm.value" :placeholder="$t('请输入值')" size="small"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" class="handle-submit">{{
          $t("确 定")
        }}</el-button>
        <el-button @click="handleCancel" class="handle-cancel">{{
          $t("取 消")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  addTemplateInfo,
  delTemplateSelect,
  addTemplateSelect,
  clearTemplateSelect,
  getTemplateInfo,
  addTemplateSelectChild
} from "@/api/system/logReport/templateReport";
import { inputClass, selectClass, texttextClass } from "@/utils/input-class.js";
import { scrollIntoView } from "@/utils/scrollIntoView";
import TempleEdit from "./TempleEdit";
export default {
  name: "TempleReportTools",
  components: {
    TempleEdit
  },
  data() {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('不能为空')));
      } else {
        callback();
      }
    };
    var validateTemplateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('不能为空')));
      } else {
        callback();
      }
    };
    return {
      templateIndex: 0,
      dialogVisible: false,
      dialogVisibleTemp: false,
      currentFlag: "", // 0是外面点击的添加  1是里面点击的添加
      conditionIndex: "",
      selectTemp: {
        condition_list: []
      },
      select: {
        condition_list: []
      },
      tableForm: {
        key: "",
        operator: "",
        value: ""
      },
      record: {
        name: "",
        show_name:"",
        desc: "",
        type: "attack-defense",
        group: "sip",
        select: []
      },
      recordCopy: {
        name: "",
        show_name:"",
        desc: "",
        type: "attack-defense",
        group: "sip",
        select: []
      },
      connector: "and",
      key: "",
      operator: "equal",
      value: "",
      typeList: {
        "attack-defense": "异常报文攻击",
        "ddos-defense": "DDOS攻击",
        "av-defense": "病毒防御",
        "content-filter": "工业审计",
        "ips-defense": "入侵防御",
        "event-type": "事件类型",
        "protocol-type": "协议类型"
      },
      groupList: {
        "attack-defense": {
          sip: "攻击源地址",
          dip: "受攻击主机",
          "event-type": "威胁攻击",
          l4type: "受影响协议"
        },
        "ddos-defense": {
          dip: "受攻击主机"
        },
        "av-defense": {
          sip: "攻击源地址",
          dip: "受攻击主机",
          "event-type": "威胁攻击",
          l4type: "受影响协议"
        },
        "content-filter": {
          sip: "源地址",
          dip: "目的地址",
          "event-type": "工业事件",
          l4type: "工业协议"
        },
        "ips-defense": {
          sip: "攻击源地址",
          dip: "受攻击主机",
          "event-type": "威胁攻击",
          l4type: "受影响协议"
        },
        "event-type": {
          "event-type": "威胁攻击"
        },
        "protocol-type": {
          l4type: "受影响协议"
        }
      },
      groupChangeSel: {
        "attack-defense": "sip",
        "ddos-defense": "dip",
        "av-defense": "sip",
        "content-filter": "sip",
        "ips-defense": "sip",
        "event-type": "event-type",
        "protocol-type": "l4type"
      },
      type: null,
      connectorList: {
        and: "与",
        or: "或"
      },
      keyList: {
        sip: "源IP",
        dip: "目的IP",
        sport: "源端口",
        dport: "目的端口"
      },
      operatorList: {
        equal: "等于",
        unequal: "不等于"
      },
      tableFormRules: {
        key: [{ required: true, message: this.$t('请输入内容'), trigger: "change" }],
        operator: [
          { required: true, message: this.$t('请输入内容'), trigger: "change" }
        ],
        value: [{ required: true, message: this.$t('请输入内容'), trigger: "blur" }]
      },
      rules: {
        name: [{ required: false, validator: validateName, trigger: "blur" }],
        interval: [
          { required: false, validator: validateName, trigger: "blur" }
        ],
        time: [{ required: false, validator: validateName, trigger: "blur" }],
        from_time: [
          { required: false, validator: validateName, trigger: "blur" }
        ],
        to_time: [
          { required: false, validator: validateName, trigger: "blur" }
        ],
        template_name: [
          {
            required: false,
            validator: validateTemplateName,
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    init(data, type) {
      this.type = type;
      this.dialogVisible = true;
      this.$nextTick(() => {
        const dataEdit = ["temValue"];
        const selectDataEdit = ["temConnector", "temKey", "temOperator"];
        inputClass(this.$refs, dataEdit);
        selectClass(this.$refs, selectDataEdit);
        if (type === "add") {
          const data = ["temName"];
          const descData = ["temDesc"];
          const selectData = ["temType", "temGroup"];
          inputClass(this.$refs, data);
          texttextClass(this.$refs, descData);
          selectClass(this.$refs, selectData);
          this.select.condition_list = [];
          this.tableForm.tableData = [];
        }
      });
      if (type === "edit") {
        this.getData(data.name);
      }
    },
    handleCancelTemp(item, index, $index) {
      if (item.type === "add") {
        this.select.condition_list[index].condition.splice($index, 1);
      }
      if (item.type === "edit") {
        this.select = JSON.parse(JSON.stringify(this.selectTemp));
        this.select.condition_list[index].condition[$index].type = "info";
        this.selectTemp = JSON.parse(JSON.stringify(this.select));
      }
    },
    handleDelTemp(item, index, $index, id) {
      this.$confirm(this.$t('您是否要删除所有选中的数据？'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: "warning"
      }).then(() => {
        // hasInfo 为true 表示请求接口回显的数据
        if (item.hasInfo) {
          const params = {
            name: this.record.name,
            id,
            key: item.key,
            operator: item.operator,
            value: item.value
          };
          console.log("params", params);
          delTemplateSelect(params).then(res => {
            this.$messages.success(this.$t('删除成功'));
            this.getData(this.record.name);
            this.$parent.listData();
          });
        } else {
          this.select.condition_list[index].condition.splice($index, 1);
          this.select.condition_list = this.select.condition_list.filter(
            item => item.condition && item.condition.length
          );
          console.log(this.select);
          this.selectTemp = JSON.parse(JSON.stringify(this.select));
        }
      });
    },
    handleSaveTemp(item, index, $index, id) {
      if (this.type === "edit") {
        const params = {
          id,
          name: this.record.name,
          ...item
        };
        console.log("params", params);
        addTemplateSelectChild(params).then(res => {
          this.$messages.success(this.$t('添加成功'));
          this.getData(this.record.name);
          this.$parent.listData();
          this.dialogVisibleTemp = false;
        });
      } else {
        this.selectTemp = JSON.parse(JSON.stringify(this.select));
        item.type = "info";
      }
    },
    handleEditTemp(item) {
      item.type = "edit";
    },
    handleAddTemp(index) {
      if (this.select.condition_list[index].condition.length === 10) {
        this.$messages.error(this.$t('一个条件内最多添加10个关键字'));
      } else {
        this.templateIndex = index;
        this.select.condition_list[index].condition.push({
          key: "",
          operator: "",
          value: "",
          type: "add"
        });
      }
    },
    handleSubmit() {
      this.$refs.tableForm.validate(valid => {
        if (valid) {
          if (this.type === "edit") {
            const params = {
              name: this.record.name,
              ...this.tableForm
            };
            console.log("params", params);
            addTemplateSelect(params).then(res => {
              this.$messages.success(this.$t('添加成功'));
              this.getData(this.record.name);
              this.$parent.listData();
              this.dialogVisibleTemp = false;
            });
          } else {
            const { key, operator, value } = this.tableForm;
            const condition = [
              {
                key,
                operator,
                value,
                type: "info"
              }
            ];
            this.select.condition_list.push({
              condition
            });
            this.selectTemp = JSON.parse(JSON.stringify(this.select));
            this.dialogVisibleTemp = false;
          }
        } else {
          return false;
        }
      });
    },
    handleCancel() {
      this.$refs.tableForm.resetFields();
      this.dialogVisibleTemp = false;
    },
    //对部分表单字段进行校验
    validateField(form) {
      let result = true;
      for (let item of this.$refs[form].fields) {
        this.$refs[form].validateField(item.prop, error => {
          if (error != "") {
            result = false;
          }
        });
      }
      return result;
    },
    getData(name) {
      getTemplateInfo({ name: name }).then(res => {
        this.record = Object.assign(this.record, res.info[0]);
        this.record.desc = this.record.des;
        console.log('this.record',this.record)
        this.select.condition_list = res.info[0].condition_list;
        this.select.condition_list.forEach(item => {
          item.condition.forEach(item => {
            item.type = "info";
            item.hasInfo = true;
          });
        });
        this.selectTemp = JSON.parse(JSON.stringify(this.select));
      });
    },
    getTemplateSelect() {
      getTemplateSelect().then(res => {
        this.selectData = res.info;
        this.selectTemp = JSON.parse(JSON.stringify(this.select));
        console.log("this.select.condition_list", this.select.condition_list);
      });
    },
    submit() {
      try {
        this.$refs.form.validate(async valid => {
          if (!this.$refs.templeEdit.validateField("tableForm")) return;
          if (valid) {
            const params = {
              name: this.record.name,
              desc: this.record.desc,
              group: this.record.group,
              type: this.record.type,
              select: JSON.stringify(this.select.condition_list)
            };
            console.log("params", params);
            const resp = await addTemplateInfo(params);
            const { status } = resp;
            if (status === 0) {
              this.$message({
                message: this.$t('添加成功'),
                type: "success"
              });
              this.close();
              this.$parent.listData();
            }
          } else {
          this.$nextTick(() => {
            scrollIntoView()
          })
            return false;
          }
        });
      } catch (err) {
        console.log(err);
      }
    },
    periodChange() {
      this.record.time = "";
      this.record.from_time = "";
      this.record.to_time = "";
      if (this.record.period === "single") {
        this.record.interval = "";
      } else {
        this.record.interval = "day";
      }
    },
    close() {
      this.type = null;
      this.record = JSON.parse(JSON.stringify(this.recordCopy));
      this.connector = "and";
      this.key = "";
      this.operator = "equal";
      this.value = "";
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    handleKeyCode(event) {
      if (event.keyCode === 13) {
        event.preventDefault(); // 阻止浏览器默认换行操作
        return false;
      }
    },
    addSelect() {
      if (!this.$refs.templeEdit.validateField("tableForm")) return;
      if (!this.$refs.templeEdit.isValidateSave()) return;
      if (this.select.condition_list.length === 5) {
        this.$message.error(this.$t('最多添加5条查询条件'));
      } else {
        this.dialogVisibleTemp = true;
      }
    },
    clearSelect() {
      this.$confirm(this.$t('您是否要清空所有条件？'), this.$t('提示'), {
        closeOnClickModal: false,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        confirmButtonClass: "confirmButton",
        cancelButtonClass: "confirmCancelButton",
        type: "warning"
      }).then(() => {
        if (this.type === "add") {
          this.record.select = [];
          this.select.condition_list = [];
        } else {
          clearTemplateSelect({ name: this.record.name }).then(res => {
            this.$messages.success(this.$t('清空成功'));
            this.getData(this.record.name);
            this.$parent.listData();
          });
        }
      });
    },
    delSelect(data) {
      this.$confirm(this.$t('您是否要删除数据？'), this.$t('提示'), {
        closeOnClickModal: false,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        confirmButtonClass: "confirmButton",
        cancelButtonClass: "confirmCancelButton",
        type: "warning"
      }).then(() => {
        if (this.type === "add") {
          this.record.select.splice(data.$index, 1);
        } else {
          let formData = Object.assign({}, data.row);
          formData.name = this.record.name;
          delTemplateSelect(formData).then(res => {
            this.$messages.success(this.$t('删除成功'));
            this.getData(this.record.name);
          });
        }
      });
    },
    typeChange() {
      this.record.group = this.groupChangeSel[this.record.type];
    }
  }
};
</script>
<style scoped lang="less">
.dialog-content-box {
  max-height: calc(80vh - 184px);
  overflow-y: auto;
}
/deep/ .el-table__body-wrapper {
  max-height: 600px;
  overflow-y: auto;
}
.table-form {
  /deep/ .el-select,
  .el-input {
    width: 100%;
  }
}
/deep/
  .el-form-item.is-required:not(.is-no-asterisk)
  > .el-form-item__label:before,
.el-form-item.is-required:not(.is-no-asterisk)
  .el-form-item__label-wrap
  > .el-form-item__label:before {
  display: none;
}
</style>
